package com.example.excel.controller;

import com.alibaba.fastjson.JSON;
import com.example.excel.data.CommonResponse;
import com.example.excel.data.TbVehicleListDto;
import com.example.excel.data.VehicleDto;
import com.example.excel.data.VehicleVo;
import com.example.excel.utils.EasyPoiUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author Aaron
 * @since 2021/7/22 14:58
 * <p>描述：</p>
 */
@RestController
@RequestMapping("/admin/vehicle")
public class VehicleGroupController {

    public static final Logger LOGGER = LoggerFactory.getLogger(VehicleGroupController.class);


    /**
     * 用户组导入失败数据缓存：parkId_"LongRentCar" <-> List<LongRentCarVo>>
     */
    private static final Map<String, List<VehicleVo>> FAILED_DATA_MAP = new HashMap<>();

    @RequestMapping("/excelTemplateDownload")
    public void excelTemplateDownload(HttpServletRequest request, HttpServletResponse response) {
        try {
            LOGGER.debug("用户组导入模板下载");
            EasyPoiUtil.VehicleGroup.downloadTemplate(request, response, false);
        } catch (Exception e) {
            LOGGER.error("用户组导入模板下载异常：", e);
        }
    }

    @RequestMapping("/vehicleExcelExport")
    public void excelExport(HttpServletRequest request, HttpServletResponse response,
                            @RequestBody VehicleVo vehicleVo) {
        try {
            LOGGER.debug("用户组导出：{}", JSON.toJSONString(vehicleVo));
            // 用户组模板数据
            List<VehicleDto> templateData = new ArrayList<>();
            VehicleDto vehicleDto = new VehicleDto();
            // 车辆名单信息集
            List<TbVehicleListDto> tbVehicleListDtoList = new ArrayList<>(1);
            vehicleDto.setTbVehicleListDtos(tbVehicleListDtoList);
            TbVehicleListDto tbVehicleListDto = new TbVehicleListDto();
            tbVehicleListDtoList.add(tbVehicleListDto);
            templateData.add(vehicleDto);
            templateData.add(vehicleDto);
            templateData.add(vehicleDto);

            // 车主信息
            vehicleDto.setParkName("Aaron_测试 3.0");
            vehicleDto.setOwnerName("张三");
            vehicleDto.setOwnerPhone("13068889887");
            vehicleDto.setOwnerAddress("中岳大街");
            vehicleDto.setOwnerCompany("二大队");
            // 车辆信息
            tbVehicleListDto.setCarNum("豫A54321");
            tbVehicleListDto.setVehicleType("1");
            tbVehicleListDto.setBeginTimeStr("2018-09-01");
            tbVehicleListDto.setEndTimeStr("2022-07-30");
            tbVehicleListDto.setFee(new BigDecimal("200"));

            EasyPoiUtil.VehicleGroup.normalDataExport(request, response, templateData, false);
        } catch (Exception e) {
            LOGGER.error("用户组导出异常：", e);
        }
    }

    @RequestMapping("/addExcelTemplateData")
    public CommonResponse<?> excelImport(@RequestParam("file") MultipartFile file, VehicleVo vehicleVo) {
        try {
            LOGGER.debug("longRentCarImport 入参：{}", JSON.toJSONString(vehicleVo));
            List<VehicleVo> list = EasyPoiUtil.VehicleGroup.excelImport(file);
            if (CollectionUtils.isEmpty(list) || list.size() > 1700) {
                LOGGER.error("用户组导入数据量异常：{} 条", CollectionUtils.isEmpty(list) ? 0 : list.size());
                return CommonResponse.error("导入记录超过1700条时，导入失败数据无法导出!建议单次导入小于1700条数据");
            }

            List<VehicleVo> importFailedList = new ArrayList<>();
            VehicleVo errData = list.get(0);
            errData.setErrField(new StringJoiner("_")
                    .add(errData.getCarNum())
                    .add(errData.getTbVehicleListDtos().toString())
                    .add("莫须有原因").toString());
            importFailedList.add(list.get(0));
            if (!CollectionUtils.isEmpty(importFailedList)) {
                LOGGER.debug("导入失败数据：{}", JSON.toJSONString(importFailedList));
                FAILED_DATA_MAP.put("_VehicleGroup", importFailedList);
                return CommonResponse.success(importFailedList.size(), "导入失败数据：" + importFailedList.size() + "条");
            }

            return CommonResponse.success(0, "导入成功");
        } catch (Exception e) {
            LOGGER.error("导入异常：", e);
            return CommonResponse.error("用户组导入异常");
        }
    }

    @RequestMapping("/failedExcelExport")
    public void failedExcelExport(HttpServletRequest request, HttpServletResponse response, @RequestBody VehicleVo vehicleVo) {
        LOGGER.debug("用户组导入失败数据下载：{}", JSON.toJSONString(vehicleVo));

        List<VehicleVo> vehicleVoList = FAILED_DATA_MAP.get("_VehicleGroup");
        if (CollectionUtils.isEmpty(vehicleVoList)) {
            LOGGER.error("用户组导入失败数据下载失败：{} 无数据", vehicleVo.getParkId());
            return;
        }

        try {
            EasyPoiUtil.VehicleGroup.failedDataExport(request, response, vehicleVoList, false);
        } catch (Exception e) {
            LOGGER.error("用户组导出失败数据异常：{} {}", vehicleVoList, e);
        }
    }

}
